package com.rwaste.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.rwaste.commonutils.Msg;
import com.rwaste.exceptionhandler.RwasteException;
import com.rwaste.vod.service.VodService;
import com.rwaste.vod.utils.ConstanVodUtils;
import com.rwaste.vod.utils.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RequestMapping("/vod")
@RestController
public class VodController {
    
    @Autowired
    private VodService vodService;

    //上传视频到阿里云
    @PostMapping("/uploadAlyVideo")
    public Msg uploadAlyVideo(MultipartFile file){
        //返回上传视频的id值
        String videoId = vodService.uploadVideoAly(file);
        return Msg.success().add("videoId", videoId);
    }

    //根据视频id删除阿里云视频
    @DeleteMapping("/removeAlyVideo/{id}")
    public Msg removeAlyVideo(@PathVariable String id){
        vodService.removeVideoAly(id);
        return Msg.success();
    }

    //根据视频id删除多个阿里云视频
    //参数时多个id
    @DeleteMapping("/removeMoreVideo")
    public Msg removeMoreVideo(List<String> videoIdList){
        vodService.removeMoreVideoAly(videoIdList);
        return Msg.success();
    }

    //根据视频id获取视频的播放凭证
    @GetMapping("/getPlayAuth/{id}")
    public Msg getPlayAuth(@PathVariable String id){
        try{
            //根据视频id获取视频播放凭证
            //创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstanVodUtils.ACCESS_KEY_ID, ConstanVodUtils.ACCESS_KEY_SECRET);

            //创建获取视频凭证request和response
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();

            //向request设置视频的id
            request.setVideoId(id);

            //调用初始化对象的方法得到凭证
            response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return Msg.success().add("playAuth", playAuth);
        }catch (Exception e){
            e.printStackTrace();
            throw new RwasteException(20001, "获取凭证失败");
        }
    }
}
